<?php

namespace common\service;

use common\exception\LogicException;
use common\model\CategoryModel;
use support\ErrorCode;
use support\SingletonTrait;
use think\Tree;

class CategoryService
{

    use SingletonTrait;

    /**
     * 分类树
     * @param $filter
     * @return array|bool
     */
    public function getCategoryTree($filter)
    {
        $list = $this->list($filter);
        if (empty($list)) {
            return $list;
        }

        $tree = new Tree('id', 'parent_id', 'children');
        $tree->load($list);
        return $tree->DeepTree();
    }

    /**
     * 列表查询
     * @param $filter
     * @param $fields
     * @return array
     */
    public function list($filter, $fields = '*')
    {
        return model(CategoryModel::class)
            ->where($filter)
            ->field($fields)
            ->order('sort_index ASC')
            ->cache(APP_DEBUG ? false : C('database.default_query_cache_time'))
            ->select();
    }

    /**
     * 获取环节包含父级信息
     * @param $categoryId
     * @return array|mixed|string
     */
    public function getCategoryWithParent($categoryId)
    {
        $category = model(CategoryModel::class)->find($categoryId);
        if (empty($category)) {
            throw new LogicException('category not found', ErrorCode::CATEGORY_NOT_FOUND);
        }
        if ($category['parent_id'] > 0) {
            $parent = model(CategoryModel::class)->find($category['parent_id']);
            $category['parent'] = $parent;
        } else {
            $category['parent'] = null;
        }
        return $category;
    }

    /**
     * 获取环节包含父级信息
     * @param $categoryIdList
     * @return array|mixed|string
     */
    public function getCategoryListWithParent($categoryIdList)
    {
        $categoryList = model(CategoryModel::class)->where(['id' => ['IN', $categoryIdList]])->select();
        if (empty($categoryList)) {
            throw new LogicException('category not found', ErrorCode::CATEGORY_NOT_FOUND);
        }
        $parentIdList = array_column($categoryList, 'parent_id', 'parent_id');
        unset($parentIdList[0]);
        $parentList = [];
        if (!empty($parentIdList)) {
            $parentList = model(CategoryModel::class)->where(['id' => ['IN', $parentIdList]])->select();
            $parentList = array_column($parentList, null, 'id');
        }
        foreach ($categoryList as &$category) {
            $category['parent'] = $parentList[$category['parent_id']] ?? null;
        }
        return $categoryList;
    }

    /**
     * 查询一个分类
     * @param $filter
     * @param $fields
     * @return array|false|mixed|string|null
     */
    public function getOne($filter, $fields)
    {
        return model(CategoryModel::class)->where($filter)->field($fields)->cache(APP_DEBUG ? false : C('database.default_query_cache_time'))->find();
    }
}
